package com.net.tomcat5;

import com.net.TCP04.char2.CloseUtil;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

/**
 * 封装响应信息
 *
 * @author jiangbang
 * @date 2016/8/24
 */
public class Response {
    //两个常量
    public static final String CRLF = "\r\n";
    public static  final String BLANK = " ";

    //正文
    private StringBuilder content;
    //存储头信息
    private StringBuilder response;
    //存储正文长度
    private int len = 0;

    public Response(){
        response = new StringBuilder();
        content = new StringBuilder();
        len = 0 ;
    }

    public Response(OutputStream os){
        this();
        bw = new BufferedWriter(new OutputStreamWriter(os));
    }


    //流
    private BufferedWriter bw;

    /**
     * 构建正文+回车
     * @param info
     * @return
     */
    public Response println(String info){
        content.append(info).append(CRLF);
        len+=(info+CRLF).getBytes().length;
        return this;
    }

    /**
     * 构建正文
     * @param info
     * @return
     */
    public Response print(String info){
        content.append(info);
        len+=info.getBytes().length;
        return this;
    }

    /**
     * 构建响应头
     */
    private void createHeadInfo(int code){
        //1.HTTP协议版本、状态代码、描述
        response.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
        switch (code){
            case 200:
                response.append("ok");
                break;
            case 404:
                response.append("NOT FOUND");
                break;
            case 500:
                response.append("SERVER ERROR");
                break;
        }
        response.append(CRLF);
        //2 响应头
        response.append("Server:jiangbang Server/0.0.1").append(CRLF);
        response.append("Date:").append(new Date()).append(CRLF);
        response.append("Content-Type:text/html;charset=UTF-8").append(CRLF);
        //正文长度：字节长度
        response.append("Content-Length").append(CRLF);
        response.append(CRLF);
    }

    //推送到客户端
    public void pushToClient(int code) throws IOException {
        createHeadInfo(code);
        //头信息+分隔符
        bw.append(response.toString());
        //正文
        bw.append(content.toString());
        bw.flush();
        CloseUtil.ColseAll(bw);
    }
}
